<?php
class NoBusinessBase_Helper_SortAndRangeExtraction
{
   public static function fetch(Zend_Controller_Request_Abstract $pRequest, $defaultSortName)
   {
      // Get range
      $range = $pRequest->getHeader('Range', 'items=0-9999999');

      // Get sort
      $sort = $pRequest->getParam('sortBy', '');

      $rangeParams = NoBusinessBase_Helper_SortAndRangeExtraction::fixRange($range);
      $sortParams = NoBusinessBase_Helper_SortAndRangeExtraction::fixSort($sort, $defaultSortName);
      return array_merge($rangeParams, $sortParams);
   }

   public static function fixRange($range)
   {
      // extract range
      $start = null;
      $limit = null;
      if($range !== false)
      {
         $range = substr($range, 6);
         $rangeParts = explode('-', $range);
         $start = $rangeParts[0];
         $limit = $rangeParts[1] - $rangeParts[0] + 1;
      }
      
      if(!$start)
         $start = 0;

      return array('start' => $start, 'limit' => $limit);
   }


   public static function fixSort($sort, $defaultSortName)
   {
      $order = 'Asc';
      if($sort == '')
      {
         $sort = $defaultSortName;
         $order = 'Desc';
      }

      if(strchr($sort,'-'))
      {
         $sort = substr($sort,1,strlen($sort));
         $order = 'Desc';
      }
      $sort = trim($sort);

      return array(
         'sort'   => $sort, 'order'  => $order,
      );
   }
}
